import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import pandas as pd
from PIL import Image, ImageTk
import sys
import os
import random

# 全局变量
is_running = False
timer_id = None
color_index = 0
colors = ["red", "blue", "green"]
data = None

def resource_path(relative_path):
    """获取资源路径"""
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

def load_data():
    """加载Excel数据"""
    global data
    file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx *.xls")])
    if file_path:
        try:
            excel_file = pd.ExcelFile(file_path, engine='openpyxl')
            sheet_names = excel_file.sheet_names
            sheet_name = select_sheet(sheet_names)
            if sheet_name:
                data = pd.read_excel(excel_file, sheet_name=sheet_name, usecols=["姓名", "帐号"], engine='openpyxl')
                result_label.config(text="数据加载成功", font=("宋体", 30), fg="black")
                add_to_history("数据加载成功")
        except Exception as e:
            messagebox.showerror("错误", f"无法加载文件: {e}")
            result_label.config(text="数据加载失败", font=("宋体", 30), fg="black")

def select_sheet(sheet_names):
    """选择工作表"""
    sheet_selection_window = tk.Toplevel(root)
    sheet_selection_window.title("选择工作表")
    sheet_selection_window.geometry("300x150")

    label = tk.Label(sheet_selection_window, text="请选择一个工作表:", font=("宋体", 12))
    label.pack(pady=10)

    sheet_var = tk.StringVar()
    sheet_combobox = ttk.Combobox(sheet_selection_window, textvariable=sheet_var, values=sheet_names, state="readonly")
    sheet_combobox.pack(pady=5)
    sheet_combobox.current(0)

    def on_select():
        sheet_selection_window.destroy()

    ok_button = tk.Button(sheet_selection_window, text="确定", command=on_select, font=("宋体", 12))
    ok_button.pack(pady=10)

    sheet_selection_window.wait_window()
    return sheet_var.get()

def random_call():
    """随机点名核心逻辑"""
    global is_running, timer_id
    if data is None:
        result_label.config(text="请先加载数据", font=("宋体", 30), fg="black")
        return
    if is_running:
        is_running = False
        button.config(text="开始")
        if timer_id:
            root.after_cancel(timer_id)
        add_to_history(result_label.cget("text"))
    else:
        is_running = True
        button.config(text="停止")
        update_random_name()

def update_random_name():
    """更新随机姓名"""
    global timer_id
    random_row = data.sample(1).iloc[0]
    name = random_row["姓名"]
    account = random_row["帐号"]
    result_label.config(text=f"{name} - {account}", font=("宋体", 35))
    blink_text()
    if is_running:
        timer_id = root.after(10, update_random_name)

def blink_text():
    """文字闪烁效果"""
    global color_index
    result_label.config(fg=colors[color_index])
    color_index = (color_index + 1) % len(colors)
    if is_running:
        root.after(100, blink_text)

def add_to_history(result):
    """添加历史记录"""
    history_text.insert(tk.END, f"{result}\n")
    history_text.see(tk.END)

def clear_history():
    """清除历史记录（带确认提示）"""
    if messagebox.askyesno("确认清除", "确定要清除所有历史记录吗？"):
        history_text.delete('1.0', tk.END)

# 创建主窗口（放在函数定义之后）
root = tk.Tk()
root.title("随机点名器")

# 设置窗口大小和位置
window_width = 500
window_height = 600
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
root.geometry(f"{window_width}x{window_height}+{x}+{y}")

# 加载图片
try:
    image = Image.open(resource_path("school_logo.jpg"))
    width, height = image.size
    new_width = 200
    new_height = int(height * (new_width / width))
    image = image.resize((new_width, new_height), Image.LANCZOS)
    photo = ImageTk.PhotoImage(image)
except Exception as e:
    messagebox.showerror("错误", f"图片加载失败: {e}")
    root.destroy()
    exit()

# 创建Logo标签
logo_label = tk.Label(root, image=photo)
logo_label.pack(side=tk.TOP, pady=10)

# 创建导入数据按钮（放在最上方）
load_button = tk.Button(root, text="导入数据", command=load_data, font=("宋体", 16))
load_button.pack(pady=20)  # 上下间距20

# 创建按钮容器（放在导入按钮下方）
button_frame = tk.Frame(root)
button_frame.pack(pady=(0, 20))  # 上间距0，下间距20

# 创建开始按钮
button = tk.Button(button_frame, text="开始", command=random_call, font=("宋体", 16))
button.pack(side=tk.LEFT, padx=15)  # 左右间距20

# 创建清除按钮（与开始按钮间隔更大）
clear_button = tk.Button(button_frame, text="清除", command=clear_history, font=("宋体", 16))
clear_button.pack(side=tk.RIGHT, padx=15)  # 右对齐，左右间距20

# 创建显示结果的标签
result_label = tk.Label(root, text="", font=("宋体", 30))
result_label.pack(pady=10)

# 创建历史记录文本框
history_text = tk.Text(root, height=10, width=30, font=("宋体", 16))
history_text.pack(pady=(0, 20))  # 上间距0，下间距20

# 绑定Enter键
root.bind('<Return>', lambda event: random_call())

# 运行主循环
root.mainloop()
